﻿#region

using System;
using System.Windows;
using Radovici.Ctrls.ContentControls;
using YouTubePlaylist.Models;
using YouTubePlaylist.MusicVideoService;

#endregion

namespace YouTubePlaylist.Views
{
    public partial class UserCtrl
    {
        #region Private fields

        private UserInputCtrl _input;
        private UserModel _vm;

        #endregion

        public UserCtrl()
        {
            InitializeComponent();
            ViewModel = new UserModel();
        }

        public UserModel ViewModel
        {
            get { return _vm; }
            private set
            {
                _vm = value;
                var element = Content as FrameworkElement;
                if (element != null)
                {
                    element.DataContext = _vm;
                }
            }
        }

        #region User dependency property

        public static readonly DependencyProperty UserProperty = DependencyProperty.Register("User", typeof (User),
                                                                                             typeof (UserCtrl),
                                                                                             new PropertyMetadata(null,
                                                                                                                  OnUserChanged));

        public User User
        {
            get { return (User) GetValue(UserProperty); }
            set { SetValue(UserProperty, value); }
        }

        private static void OnUserChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var ctrl = d as UserCtrl;
            if (ctrl != null)
            {
                ctrl.ViewModel.User = e.NewValue as User; //= new UserModel(e.NewValue as User);
            }
        }

        #endregion

        #region Private methods

        private void OnLoginClicked(object sender, RoutedEventArgs e)
        {
            _input = new UserInputCtrl(ViewModel.User);
            var widget = new Widget
                             {
                                 Content = _input,
                                 Title = "User Login",
                                 OkEnabled = true
                             };
            widget.Show(OnUserChanged, sender as UIElement);
        }

        private void OnUserChanged(object sender, EventArgs e)
        {
            var ctrl = sender as Widget;
            if (ctrl != null)
            {
                var userInputCtrl = ctrl.Content as UserInputCtrl;
                if (userInputCtrl != null)
                {
                    ViewModel.User.ExternalKey = userInputCtrl.Email.Text;
                }
            }
        }

        #endregion
    }
}